<template>
  <div class="create-plan-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span v-if="mode === 'view'">查看康复计划</span>
          <span v-else-if="mode === 'edit'">修改康复计划</span>
          <span v-else>制定康复计划</span>
        </div>
      </template>

      <!-- 上下文信息区 -->
      <el-descriptions title="基础信息" :column="2" border class="context-info">
        <el-descriptions-item label="报告ID">{{ reportInfo.id }}</el-descriptions-item>
        <el-descriptions-item label="学生姓名">{{ reportInfo.studentName }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ reportInfo.studentNumber }}</el-descriptions-item>
        <el-descriptions-item label="伤病报告标题">{{ reportInfo.title }}</el-descriptions-item>
        <el-descriptions-item label="受伤部位">{{ reportInfo.bodyPart }}</el-descriptions-item>
        <el-descriptions-item label="严重程度">{{ reportInfo.severity }}</el-descriptions-item>
        <el-descriptions-item label="受伤日期">{{ reportInfo.injuryTime }}</el-descriptions-item>
        <el-descriptions-item label="伤病描述" :span="2" v-if="reportInfo.description">{{
          reportInfo.description
        }}</el-descriptions-item>
      </el-descriptions>

      <!-- 伤病图片展示区 -->
      <div v-if="injuryImagesDisplay.length > 0" class="injury-images-section">
        <el-divider content-position="left"><h3>伤病照片</h3></el-divider>
        <div class="image-gallery">
          <div
            v-for="(url, index) in injuryImagesDisplay"
            :key="index"
            class="image-item"
            @click="previewImageDisplay(url)"
          >
            <el-image :src="url" fit="cover" style="width: 100%; height: 100%" lazy>
              <template #error>
                <div class="image-slot-error">
                  <el-icon><Picture /></el-icon> 图片加载失败
                </div>
              </template>
            </el-image>
          </div>
        </div>
      </div>
      <div v-else-if="reportInfo.id !== 'N/A'" class="injury-images-section">
        <el-divider content-position="left"><h3>伤病照片</h3></el-divider>
        <el-empty description="暂无伤病照片" :image-size="100"></el-empty>
      </div>

      <!-- 康复计划表单区 -->
      <el-form
        :model="formData"
        :rules="mode === 'view' ? undefined : rules"
        ref="planFormRef"
        label-width="120px"
        :disabled="mode === 'view'"
        :validate-on-rule-change="mode !== 'view'"
        :hide-required-asterisk="mode === 'view'"
        class="plan-form"
      >
        <el-divider content-position="left"><h3>计划详情</h3></el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划标题" prop="title" :rules="rules['title']">
              <el-input
                v-model="formData.title"
                placeholder="例如：XX同学的膝关节术后第一阶段康复计划"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划制定日期" prop="planDate">
              <el-date-picker
                v-model="formData.planDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划开始日期" prop="startDate" :rules="rules['startDate']">
              <el-date-picker
                v-model="formData.startDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计结束日期" prop="endDate">
              <el-date-picker
                v-model="formData.endDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="康复总目标" prop="overallGoal" :rules="rules['overallGoal']">
          <el-input
            v-model="formData.overallGoal"
            type="textarea"
            :rows="3"
            placeholder="例如：恢复完整的膝关节活动度，增强股四头肌力量"
          ></el-input>
        </el-form-item>

        <el-divider content-position="left">
          <h4>训练项目</h4>
        </el-divider>

        <!-- 训练项目 -->
        <div
          v-for="(exercise, index) in formData.exercises"
          :key="index"
          class="exercise-item"
          :class="{ 'exercise-item-even': index % 2 === 0 }"
        >
          <div class="exercise-header">
            <h4>训练项目 {{ index + 1 }}</h4>
            <el-button
              v-if="index > 0 && mode !== 'view'"
              type="danger"
              size="small"
              circle
              @click="removeExercise(index)"
              :icon="Delete"
              class="delete-btn"
            ></el-button>
          </div>

          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item
                :label="'项目名称'"
                :prop="'exercises.' + index + '.name'"
                :rules="
                  index === 0
                    ? [{ required: true, message: '请输入训练项目名称', trigger: 'blur' }]
                    : []
                "
              >
                <el-input v-model="exercise.name" placeholder="例如：直腿抬高"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item :label="'组数'" :prop="'exercises.' + index + '.sets'">
                <el-input-number
                  v-model="exercise.sets"
                  :min="1"
                  placeholder="组"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item :label="'次数'" :prop="'exercises.' + index + '.reps'">
                <el-input-number
                  v-model="exercise.reps"
                  :min="0"
                  placeholder="次"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="'频率'" :prop="'exercises.' + index + '.frequency'">
                <el-input v-model="exercise.frequency" placeholder="例如：每日2次"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item :label="'时长(秒)'" :prop="'exercises.' + index + '.duration'">
                <el-input-number
                  v-model="exercise.duration"
                  :min="0"
                  placeholder="秒"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item :label="'备注'" :prop="'exercises.' + index + '.notes'">
                <el-input
                  v-model="exercise.notes"
                  placeholder="关于此训练项目的额外说明"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item :label="'动作描述'" :prop="'exercises.' + index + '.description'">
            <el-input
              v-model="exercise.description"
              type="textarea"
              :rows="2"
              placeholder="简述动作要点"
            ></el-input>
          </el-form-item>
        </div>

        <div class="add-exercise" v-if="formData.exercises.length < 5 && mode !== 'view'">
          <el-button type="primary" plain @click="addExercise">
            <el-icon><Plus /></el-icon> 添加训练项目
          </el-button>
        </div>

        <el-divider content-position="left"><h4>其他信息</h4></el-divider>
        <el-form-item label="总体建议/医嘱" prop="recommendations">
          <el-input
            v-model="formData.recommendations"
            type="textarea"
            :rows="3"
            placeholder="例如：注意休息，避免剧烈运动，如有不适立即停止训练并联系康复师"
          ></el-input>
        </el-form-item>

        <el-form-item label="制定人">
          <el-input v-model="formData.creatorName" disabled></el-input>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区 -->
      <div class="action-buttons">
        <template v-if="mode === 'view'">
          <el-button @click="router.back()">返回</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="handleSavePlan" :loading="saving">
            {{ mode === 'edit' ? '保存修改' : '保存计划' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </template>
      </div>
    </el-card>
  </div>

  <!-- 图片预览 -->
  <el-image-viewer
    v-if="previewVisibleDisplay"
    :url-list="[previewImageUrlDisplay]"
    @close="previewVisibleDisplay = false"
    :initial-index="0"
    :infinite="false"
    :hide-on-click-modal="true"
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, Picture } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import request from '@/utils/request'
import {
  addRehabilitationPlan,
  updateRehabilitationPlan,
  getRehabilitationPlan,
  getInjuryRehabilitationList,
} from '@/api/plan'
import { getCurrentUser } from '@/api/user'

interface ReportInfo {
  id: string
  studentName: string
  studentNumber: string
  title: string
  bodyPart: string
  severity: string
  injuryTime: string
  description?: string
  injuryImage1?: string | null
  injuryImage2?: string | null
  injuryImage3?: string | null
  injuryImage4?: string | null
  injuryImage5?: string | null
  injuryImage6?: string | null
  studentId?: string | number
}

interface Exercise {
  name: string
  description: string
  sets: number | undefined
  reps: number | undefined
  frequency: string
  duration: number | undefined
  notes: string
}

interface PlanForm {
  reportId: string
  studentId: string
  title: string
  planDate: string
  startDate: string
  endDate: string
  overallGoal: string
  recommendations: string
  followUpDate: string
  status: string
  creatorName: string
  creatorId: number | undefined
  exercises: Exercise[]
}

const route = useRoute()
const router = useRouter()
const planFormRef = ref<FormInstance>()
const saving = ref(false)
const mode = ref('create') // 默认为创建模式，其他可能值: 'edit', 'view'
const existingPlanId = ref<number | null>(null) // 用于存储现有康复计划ID，编辑模式使用

// 表单验证规则
const rules = reactive({
  title: [{ required: true, message: '请输入计划标题', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择计划开始日期', trigger: 'change' }],
  overallGoal: [{ required: true, message: '请输入康复总目标', trigger: 'blur' }],
  'exercises.0.name': [{ required: true, message: '请输入训练项目名称', trigger: 'blur' }],
})

const reportInfo = ref<ReportInfo>({
  id: 'N/A',
  studentName: '-',
  studentNumber: '-',
  title: '-',
  bodyPart: '-',
  severity: '-',
  injuryTime: '-',
  description: '-',
  injuryImage1: null,
  injuryImage2: null,
  injuryImage3: null,
  injuryImage4: null,
  injuryImage5: null,
  injuryImage6: null,
  studentId: undefined,
})

// 将planForm改造为包含exercises
const formData = reactive<PlanForm>({
  reportId: '',
  studentId: '',
  title: '',
  planDate: new Date().toISOString().split('T')[0],
  startDate: '',
  endDate: '',
  overallGoal: '',
  recommendations: '',
  followUpDate: '',
  status: '草稿',
  creatorName: '管理员用户',
  creatorId: undefined,
  exercises: [
    {
      name: '',
      description: '',
      sets: 1,
      reps: 0,
      frequency: '',
      duration: 0,
      notes: '',
    },
  ],
})

// 添加训练项目
const addExercise = () => {
  if (formData.exercises.length < 5) {
    formData.exercises.push({
      name: '',
      description: '',
      sets: 1,
      reps: 0,
      frequency: '',
      duration: 0,
      notes: '',
    })
  } else {
    ElMessage.warning('最多只能添加5个训练项目')
  }
}

// 删除训练项目
const removeExercise = (index: number) => {
  if (index > 0) {
    // 不允许删除第一个训练项目
    formData.exercises.splice(index, 1)
  }
}

const injuryImagesDisplay = ref<string[]>([])
const previewVisibleDisplay = ref(false)
const previewImageUrlDisplay = ref('')

const fetchReportDetails = async (id: string) => {
  if (!id || id === 'N/A') {
    ElMessage.error('未提供有效的伤病报告ID')
    return
  }
  console.log(`获取ID为 ${id} 的伤病报告详情...`)
  try {
    const response = await request.get(`/injury/report/detail/${id}`)
    const data = response.data

    if (data && data.id) {
      reportInfo.value = {
        id: data.id?.toString() || id,
        studentName: data.username || data.student?.username || '-',
        studentNumber: data.studentNumber || data.student?.studentNumber || '-',
        title: data.title || '-',
        bodyPart: data.bodyPart || '-',
        severity: data.severity || '-',
        injuryTime: data.injuryTime || '-',
        description: data.description || '-',
        injuryImage1: data.injuryImage1 || null,
        injuryImage2: data.injuryImage2 || null,
        injuryImage3: data.injuryImage3 || null,
        injuryImage4: data.injuryImage4 || null,
        injuryImage5: data.injuryImage5 || null,
        injuryImage6: data.injuryImage6 || null,
        studentId: data.userId || data.student?.id || null,
      }

      const images = [
        reportInfo.value.injuryImage1,
        reportInfo.value.injuryImage2,
        reportInfo.value.injuryImage3,
        reportInfo.value.injuryImage4,
        reportInfo.value.injuryImage5,
        reportInfo.value.injuryImage6,
      ].filter((url): url is string => typeof url === 'string' && url.trim() !== '')
      injuryImagesDisplay.value = images

      if (!formData.title) {
        formData.title = `${reportInfo.value.studentName} - ${reportInfo.value.bodyPart} 康复计划`
      }
      formData.reportId = reportInfo.value.id

      // 如果有studentId，设置到formData中
      if (reportInfo.value.studentId) {
        formData.studentId = reportInfo.value.studentId.toString()
      }
    } else {
      ElMessage.error('获取伤病报告详情失败或数据格式不正确')
      console.warn('伤病报告详情API返回数据:', data)
    }
  } catch (error) {
    console.error('获取伤病报告详情出错:', error)
    ElMessage.error('获取伤病报告详情过程中发生错误')
  }
}

const fetchCurrentUser = async () => {
  console.log('获取当前登录用户信息...')
  try {
    const response = await getCurrentUser()
    if (response && response.code === 200 && response.data) {
      formData.creatorName = response.data.username || '未知用户'
      formData.creatorId = response.data.id
      console.log('当前登录用户:', response.data)
    } else {
      console.error('获取当前用户信息失败:', response)
      formData.creatorName = '获取失败'
    }
  } catch (error) {
    console.error('获取当前用户信息出错:', error)
    formData.creatorName = '获取失败'
  }
}

// 获取已有的康复计划 (用于编辑和查看模式)
const fetchExistingPlan = async (reportId: string) => {
  try {
    console.log(`获取伤病报告 ${reportId} 关联的康复计划...`)
    // 使用API获取与伤病报告关联的康复计划列表
    const listResponse = await getInjuryRehabilitationList(reportId ? reportId : '0')

    if (listResponse.code === 200 && listResponse.data && listResponse.data.length > 0) {
      const planId = listResponse.data[0].id // 获取第一个关联计划的ID
      console.log(`找到关联康复计划ID: ${planId}，获取详情...`)

      // 使用API获取康复计划详情
      const detailResponse = await getRehabilitationPlan(planId ? planId : 0)

      if (detailResponse.code === 200 && detailResponse.data) {
        const plan = detailResponse.data
        console.log('获取到康复计划详情:', plan)

        // 填充表单数据
        formData.title = plan.title || ''
        formData.overallGoal = plan.description || ''
        formData.startDate = plan.startDate || ''
        formData.endDate = plan.endDate || ''
        formData.recommendations = plan.item1Notes || '' // 使用第一个训练项目的注释作为总体建议

        // 记录计划ID，用于编辑时更新
        if (plan.id) {
          console.log(`设置计划ID: ${plan.id}`)
          existingPlanId.value = Number(plan.id)
        }

        // 填充训练项目
        formData.exercises = []

        // 处理训练项目1
        if (plan.item1Name) {
          formData.exercises.push({
            name: plan.item1Name || '',
            description: plan.item1Description || '',
            sets: plan.item1Sets || 0,
            reps: plan.item1Repetitions || 0,
            frequency: plan.item1Frequency || '',
            duration: plan.item1Duration || 0,
            notes: plan.item1Notes || '',
          })
        }

        // 处理训练项目2
        if (plan.item2Name) {
          formData.exercises.push({
            name: plan.item2Name || '',
            description: plan.item2Description || '',
            sets: plan.item2Sets || 0,
            reps: plan.item2Repetitions || 0,
            frequency: plan.item2Frequency || '',
            duration: plan.item2Duration || 0,
            notes: plan.item2Notes || '',
          })
        }

        // 处理训练项目3
        if (plan.item3Name) {
          formData.exercises.push({
            name: plan.item3Name || '',
            description: plan.item3Description || '',
            sets: plan.item3Sets || 0,
            reps: plan.item3Repetitions || 0,
            frequency: plan.item3Frequency || '',
            duration: plan.item3Duration || 0,
            notes: plan.item3Notes || '',
          })
        }

        // 处理训练项目4
        if (plan.item4Name) {
          formData.exercises.push({
            name: plan.item4Name || '',
            description: plan.item4Description || '',
            sets: plan.item4Sets || 0,
            reps: plan.item4Repetitions || 0,
            frequency: plan.item4Frequency || '',
            duration: plan.item4Duration || 0,
            notes: plan.item4Notes || '',
          })
        }

        // 处理训练项目5
        if (plan.item5Name) {
          formData.exercises.push({
            name: plan.item5Name || '',
            description: plan.item5Description || '',
            sets: plan.item5Sets || 0,
            reps: plan.item5Repetitions || 0,
            frequency: plan.item5Frequency || '',
            duration: plan.item5Duration || 0,
            notes: plan.item5Notes || '',
          })
        }

        // 如果没有训练项目，添加一个空的
        if (formData.exercises.length === 0) {
          formData.exercises.push({
            name: '',
            description: '',
            sets: 1,
            reps: 0,
            frequency: '',
            duration: 0,
            notes: '',
          })
        }

        return true
      } else {
        console.warn('获取康复计划详情失败:', detailResponse)
        return false
      }
    } else {
      console.warn('没有找到关联的康复计划:', listResponse)
      return false
    }
  } catch (error) {
    console.error('获取康复计划失败:', error)
    ElMessage.error('获取康复计划数据失败')
    return false
  }
}

onMounted(async () => {
  // 获取路由参数
  const reportIdFromRoute = (route.params.reportId as string) || (route.query.reportId as string)
  const modeFromRoute = (route.query.mode as string) || 'create'

  // 设置页面模式
  mode.value = ['view', 'edit'].includes(modeFromRoute) ? modeFromRoute : 'create'
  console.log(`页面模式: ${mode.value}, 报告ID: ${reportIdFromRoute}`)

  if (reportIdFromRoute) {
    // 获取伤病报告详情
    await fetchReportDetails(reportIdFromRoute)

    // 如果是编辑或查看模式，获取已有的康复计划
    if (mode.value === 'edit' || mode.value === 'view') {
      const hasPlan = await fetchExistingPlan(reportIdFromRoute)
      if (!hasPlan && mode.value === 'view') {
        ElMessage.warning('未找到关联的康复计划，将以新建模式打开')
        mode.value = 'create'
      }
    }
  } else {
    ElMessage.warning('未在路由参数中找到 reportId，请确保从正确的入口进入此页面。')
  }

  // 获取当前用户信息
  await fetchCurrentUser()
})

const handleSavePlan = async () => {
  if (!planFormRef.value) return

  // 查看模式下不需要验证
  if (mode.value === 'view') {
    router.back()
    return
  }

  planFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saving.value = true

      try {
        // 打印验证数据，帮助调试
        console.log('原始表单数据:', JSON.stringify(formData))

        // 检查并确保学生ID有效
        if (!formData.studentId || parseInt(formData.studentId.toString()) <= 0) {
          ElMessage.warning('未找到有效的学生ID，请确保伤病报告包含学生信息')
          saving.value = false
          return
        }

        // 确保reportId有效
        const reportId = parseInt(formData.reportId) || 0
        if (reportId <= 0) {
          ElMessage.warning('未找到有效的伤病报告ID')
          saving.value = false
          return
        }

        // 检查第一个训练项目是否填写
        if (!formData.exercises[0]?.name) {
          ElMessage.warning('请至少填写一个训练项目的名称')
          saving.value = false
          return
        }

        // 将前端表单数据转换为后端API所需格式
        const planData: Partial<import('@/api/plan').RehabilitationPlanData> = {
          patientId: parseInt(formData.studentId.toString()),
          therapistId: formData.creatorId || 0,
          title: formData.title,
          description: formData.overallGoal,
          injuryReportId: reportId,
          startDate: formData.startDate,
          endDate: formData.endDate,
          status: 0, // 必须的字段，接口要求，默认为草稿状态

          // 处理训练项目数据，确保正确转换数字类型
          item1Name: formData.exercises[0]?.name || '',
          item1Description: formData.exercises[0]?.description || '',
          item1Frequency: formData.exercises[0]?.frequency || '',
          item1Sets: Number(formData.exercises[0]?.sets) || 0,
          item1Repetitions: Number(formData.exercises[0]?.reps) || 0,
          item1Duration: Number(formData.exercises[0]?.duration) || 0,
          item1Notes: formData.exercises[0]?.notes || '',

          // 训练项目2（可选）
          item2Name: formData.exercises.length > 1 ? formData.exercises[1].name || '' : '',
          item2Description:
            formData.exercises.length > 1 ? formData.exercises[1].description || '' : '',
          item2Frequency:
            formData.exercises.length > 1 ? formData.exercises[1].frequency || '' : '',
          item2Sets: formData.exercises.length > 1 ? Number(formData.exercises[1].sets) || 0 : 0,
          item2Repetitions:
            formData.exercises.length > 1 ? Number(formData.exercises[1].reps) || 0 : 0,
          item2Duration:
            formData.exercises.length > 1 ? Number(formData.exercises[1].duration) || 0 : 0,
          item2Notes: formData.exercises.length > 1 ? formData.exercises[1].notes || '' : '',

          // 训练项目3（可选）
          item3Name: formData.exercises.length > 2 ? formData.exercises[2].name || '' : '',
          item3Description:
            formData.exercises.length > 2 ? formData.exercises[2].description || '' : '',
          item3Frequency:
            formData.exercises.length > 2 ? formData.exercises[2].frequency || '' : '',
          item3Sets: formData.exercises.length > 2 ? Number(formData.exercises[2].sets) || 0 : 0,
          item3Repetitions:
            formData.exercises.length > 2 ? Number(formData.exercises[2].reps) || 0 : 0,
          item3Duration:
            formData.exercises.length > 2 ? Number(formData.exercises[2].duration) || 0 : 0,
          item3Notes: formData.exercises.length > 2 ? formData.exercises[2].notes || '' : '',

          // 训练项目4（可选）
          item4Name: formData.exercises.length > 3 ? formData.exercises[3].name || '' : '',
          item4Description:
            formData.exercises.length > 3 ? formData.exercises[3].description || '' : '',
          item4Frequency:
            formData.exercises.length > 3 ? formData.exercises[3].frequency || '' : '',
          item4Sets: formData.exercises.length > 3 ? Number(formData.exercises[3].sets) || 0 : 0,
          item4Repetitions:
            formData.exercises.length > 3 ? Number(formData.exercises[3].reps) || 0 : 0,
          item4Duration:
            formData.exercises.length > 3 ? Number(formData.exercises[3].duration) || 0 : 0,
          item4Notes: formData.exercises.length > 3 ? formData.exercises[3].notes || '' : '',

          // 训练项目5（可选）
          item5Name: formData.exercises.length > 4 ? formData.exercises[4].name || '' : '',
          item5Description:
            formData.exercises.length > 4 ? formData.exercises[4].description || '' : '',
          item5Frequency:
            formData.exercises.length > 4 ? formData.exercises[4].frequency || '' : '',
          item5Sets: formData.exercises.length > 4 ? Number(formData.exercises[4].sets) || 0 : 0,
          item5Repetitions:
            formData.exercises.length > 4 ? Number(formData.exercises[4].reps) || 0 : 0,
          item5Duration:
            formData.exercises.length > 4 ? Number(formData.exercises[4].duration) || 0 : 0,
          item5Notes: formData.exercises.length > 4 ? formData.exercises[4].notes || '' : '',

          // 进度记录
          progressStatus: 0, // 默认未开始
          progressNotes: '',
        }

        console.log('发送到后端API的康复计划数据:', planData)

        let response
        if (mode.value === 'edit') {
          // 编辑模式下调用更新API
          console.log('修改康复计划...')

          // 确保有计划ID
          if (!existingPlanId.value) {
            ElMessage.error('无法修改康复计划：缺少计划ID')
            saving.value = false
            return
          }

          // 添加ID到数据中
          planData.id = existingPlanId.value

          // 使用API函数更新
          response = await updateRehabilitationPlan(
            planData as import('@/api/plan').RehabilitationPlanData,
          )
          if (response.code === 200) {
            ElMessage.success('康复计划已更新成功！')
            router.back()
          } else {
            ElMessage.error(`更新失败: ${response.message || '未知错误'}`)
            console.error('API响应:', response)
          }
        } else {
          // 新建模式调用添加API
          console.log('新建康复计划...')
          response = await addRehabilitationPlan(
            planData as import('@/api/plan').RehabilitationPlanData,
          )
          // response已经是经过请求处理的响应对象
          if (response.code === 200) {
            ElMessage.success('康复计划已保存成功！')
            router.back()
          } else {
            ElMessage.error(`保存失败: ${response.message || '未知错误'}`)
            console.error('API响应:', response)
          }
        }
      } catch (error) {
        console.error('保存康复计划出错:', error)
        ElMessage.error('保存康复计划过程中发生错误')
      } finally {
        saving.value = false
      }
    } else {
      console.error('表单验证失败')
      ElMessage.error('表单验证失败，请检查输入项。')
      // 打印验证错误详情
      setTimeout(() => {
        if (planFormRef.value) {
          planFormRef.value.validate((valid, fields) => {
            console.log('验证结果:', valid, fields)
          })
        }
      }, 100)
    }
  })
}

const handleCancel = () => {
  ElMessageBox.confirm('您确定要取消编辑吗？所有未保存的更改都将丢失。', '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '点错了',
    type: 'warning',
  })
    .then(() => {
      router.back()
    })
    .catch(() => {
      ElMessage.info('已取消操作')
    })
}

const previewImageDisplay = (url: string) => {
  previewImageUrlDisplay.value = url
  previewVisibleDisplay.value = true
}
</script>

<style scoped>
.create-plan-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.context-info {
  margin-bottom: 20px;
}

.injury-images-section {
  margin-bottom: 30px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 15px; /*  Space between images */
}

.image-item {
  width: 120px; /* Adjust size as needed */
  height: 120px; /* Adjust size as needed */
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #ebeef5;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-item .el-image {
  display: block; /* Fixes potential small gaps */
}

.image-slot-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
  font-size: 14px;
}
.image-slot-error .el-icon {
  font-size: 30px;
  margin-bottom: 5px;
}

.plan-form {
  margin-top: 20px;
}
.exercise-item {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 30px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
}

.exercise-item-even {
  background-color: #f5f7fa;
}
.exercise-item .el-form-item {
  margin-bottom: 16px;
}
.exercise-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.exercise-header h4 {
  margin: 0;
}
.delete-btn {
  margin-right: 10px;
}
.add-exercise {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
.action-buttons {
  margin-top: 30px;
  text-align: center;
}
.el-divider h3,
.el-divider h4 {
  margin: 0;
  color: #303133;
}
.el-divider {
  margin: 30px 0;
}
</style>
